Cockroaches

Recap

We are analysing data about complaints for the presence of cocroaches in 10 residential buildings. Using a Bayesian framework, we modelled the number of complaints using a Poisson model. Diagnostic analysis of the model highlights some residual variability. We decided to try to improve our estimates adding one predictor and an exposure term to the Poisson model, but the situation did not improve. The ‘Poisson’ assumption on the model variance turned out to be too restrictive to model our data. The Negative Binomial model gave better results, but examining the standardized residual plot we noticed that some of them were still very large.

A posterior predictive check considering that the data are clustered by building.

library(rstan)
library(dplyr)
library(lubridate)
library(ggplot2)
library(bayesplot)

theme_set(bayesplot::theme_default())
rstan_options(auto_write=TRUE)
pest_data <- readRDS('pest_data.RDS')
str(pest_data)
## 'data.frame':    120 obs. of  14 variables:
##  $ mus                 : num  0.369 0.359 0.282 0.129 0.452 ...
##  $ building_id         : int  37 37 37 37 37 37 37 37 37 37 ...
##  $ wk_ind              : int  1 2 3 4 5 6 7 8 9 10 ...
##  $ date                : Date, format: "2017-01-15" "2017-02-14" ...
##  $ traps               : num  8 8 9 10 11 11 10 10 9 9 ...
##  $ floors              : num  8 8 8 8 8 8 8 8 8 8 ...
##  $ sq_footage_p_floor  : num  5149 5149 5149 5149 5149 ...
##  $ live_in_super       : num  0 0 0 0 0 0 0 0 0 0 ...
##  $ monthly_average_rent: num  3847 3847 3847 3847 3847 ...
##  $ average_tenant_age  : num  53.9 53.9 53.9 53.9 53.9 ...
##  $ age_of_building     : num  47 47 47 47 47 47 47 47 47 47 ...
##  $ total_sq_foot       : num  41192 41192 41192 41192 41192 ...
##  $ month               : num  1 2 3 4 5 6 7 8 9 10 ...
##  $ complaints          : num  1 3 0 1 0 0 4 3 2 2 ...
summary(pest_data)
##       mus           building_id       wk_ind           date           
##  Min.   :-0.1008   Min.   : 5.0   Min.   : 1.00   Min.   :2017-01-15  
##  1st Qu.: 0.5279   1st Qu.:26.0   1st Qu.: 3.75   1st Qu.:2017-04-07  
##  Median : 1.0422   Median :46.0   Median : 6.50   Median :2017-06-29  
##  Mean   : 1.1116   Mean   :49.6   Mean   : 6.50   Mean   :2017-06-29  
##  3rd Qu.: 1.6837   3rd Qu.:70.0   3rd Qu.: 9.25   3rd Qu.:2017-09-19  
##  Max.   : 2.8030   Max.   :98.0   Max.   :12.00   Max.   :2017-12-11  
##      traps            floors     sq_footage_p_floor live_in_super
##  Min.   : 1.000   Min.   : 4.0   Min.   :4186       Min.   :0.0  
##  1st Qu.: 6.000   1st Qu.: 8.0   1st Qu.:4770       1st Qu.:0.0  
##  Median : 7.000   Median :10.0   Median :5097       Median :0.0  
##  Mean   : 7.033   Mean   : 9.9   Mean   :4991       Mean   :0.3  
##  3rd Qu.: 8.000   3rd Qu.:13.0   3rd Qu.:5206       3rd Qu.:1.0  
##  Max.   :11.000   Max.   :15.0   Max.   :5740       Max.   :1.0  
##  monthly_average_rent average_tenant_age age_of_building total_sq_foot  
##  Min.   :3029         Min.   :41.14      Min.   :39.0    Min.   :19217  
##  1st Qu.:3564         1st Qu.:45.14      1st Qu.:47.0    1st Qu.:41192  
##  Median :3813         Median :48.20      Median :49.0    Median :47096  
##  Mean   :3687         Mean   :49.92      Mean   :49.4    Mean   :49248  
##  3rd Qu.:3864         3rd Qu.:53.88      3rd Qu.:51.0    3rd Qu.:59251  
##  Max.   :4019         Max.   :65.18      Max.   :60.0    Max.   :78093  
##      month         complaints    
##  Min.   : 1.00   Min.   : 0.000  
##  1st Qu.: 3.75   1st Qu.: 1.000  
##  Median : 6.50   Median : 2.000  
##  Mean   : 6.50   Mean   : 3.658  
##  3rd Qu.: 9.25   3rd Qu.: 5.250  
##  Max.   :12.00   Max.   :18.000
##number of buildings
N_buildings <- length(unique(pest_data$building_id))
N_buildings
## [1] 10
## arrange data into a list
stan_dat_simple <- list(
  N = nrow(pest_data), 
  complaints = pest_data$complaints,
  traps = pest_data$traps,
  log_sq_foot = log(pest_data$total_sq_foot/1e4),
  live_in_super = pest_data$live_in_super
)
str(stan_dat_simple)
## List of 5
##  $ N            : int 120
##  $ complaints   : num [1:120] 1 3 0 1 0 0 4 3 2 2 ...
##  $ traps        : num [1:120] 8 8 9 10 11 11 10 10 9 9 ...
##  $ log_sq_foot  : num [1:120] 1.42 1.42 1.42 1.42 1.42 ...
##  $ live_in_super: num [1:120] 0 0 0 0 0 0 0 0 0 0 ...
comp_model_NB <- stan_model('multiple_NB_regression.stan')
fitted_model_NB <- sampling(comp_model_NB, data = stan_dat_simple)
## 
## SAMPLING FOR MODEL 'multiple_NB_regression' NOW (CHAIN 1).
## Chain 1: 
## Chain 1: Gradient evaluation took 8.4e-05 seconds
## Chain 1: 1000 transitions using 10 leapfrog steps per transition would take 0.84 seconds.
## Chain 1: Adjust your expectations accordingly!
## Chain 1: 
## Chain 1: 
## Chain 1: Iteration:    1 / 2000 [  0%]  (Warmup)
## Chain 1: Iteration:  200 / 2000 [ 10%]  (Warmup)
## Chain 1: Iteration:  400 / 2000 [ 20%]  (Warmup)
## Chain 1: Iteration:  600 / 2000 [ 30%]  (Warmup)
## Chain 1: Iteration:  800 / 2000 [ 40%]  (Warmup)
## Chain 1: Iteration: 1000 / 2000 [ 50%]  (Warmup)
## Chain 1: Iteration: 1001 / 2000 [ 50%]  (Sampling)
## Chain 1: Iteration: 1200 / 2000 [ 60%]  (Sampling)
## Chain 1: Iteration: 1400 / 2000 [ 70%]  (Sampling)
## Chain 1: Iteration: 1600 / 2000 [ 80%]  (Sampling)
## Chain 1: Iteration: 1800 / 2000 [ 90%]  (Sampling)
## Chain 1: Iteration: 2000 / 2000 [100%]  (Sampling)
## Chain 1: 
## Chain 1:  Elapsed Time: 1.01936 seconds (Warm-up)
## Chain 1:                0.859583 seconds (Sampling)
## Chain 1:                1.87895 seconds (Total)
## Chain 1: 
## 
## SAMPLING FOR MODEL 'multiple_NB_regression' NOW (CHAIN 2).
## Chain 2: 
## Chain 2: Gradient evaluation took 9.3e-05 seconds
## Chain 2: 1000 transitions using 10 leapfrog steps per transition would take 0.93 seconds.
## Chain 2: Adjust your expectations accordingly!
## Chain 2: 
## Chain 2: 
## Chain 2: Iteration:    1 / 2000 [  0%]  (Warmup)
## Chain 2: Iteration:  200 / 2000 [ 10%]  (Warmup)
## Chain 2: Iteration:  400 / 2000 [ 20%]  (Warmup)
## Chain 2: Iteration:  600 / 2000 [ 30%]  (Warmup)
## Chain 2: Iteration:  800 / 2000 [ 40%]  (Warmup)
## Chain 2: Iteration: 1000 / 2000 [ 50%]  (Warmup)
## Chain 2: Iteration: 1001 / 2000 [ 50%]  (Sampling)
## Chain 2: Iteration: 1200 / 2000 [ 60%]  (Sampling)
## Chain 2: Iteration: 1400 / 2000 [ 70%]  (Sampling)
## Chain 2: Iteration: 1600 / 2000 [ 80%]  (Sampling)
## Chain 2: Iteration: 1800 / 2000 [ 90%]  (Sampling)
## Chain 2: Iteration: 2000 / 2000 [100%]  (Sampling)
## Chain 2: 
## Chain 2:  Elapsed Time: 0.994465 seconds (Warm-up)
## Chain 2:                0.921595 seconds (Sampling)
## Chain 2:                1.91606 seconds (Total)
## Chain 2: 
## 
## SAMPLING FOR MODEL 'multiple_NB_regression' NOW (CHAIN 3).
## Chain 3: 
## Chain 3: Gradient evaluation took 0.000102 seconds
## Chain 3: 1000 transitions using 10 leapfrog steps per transition would take 1.02 seconds.
## Chain 3: Adjust your expectations accordingly!
## Chain 3: 
## Chain 3: 
## Chain 3: Iteration:    1 / 2000 [  0%]  (Warmup)
## Chain 3: Iteration:  200 / 2000 [ 10%]  (Warmup)
## Chain 3: Iteration:  400 / 2000 [ 20%]  (Warmup)
## Chain 3: Iteration:  600 / 2000 [ 30%]  (Warmup)
## Chain 3: Iteration:  800 / 2000 [ 40%]  (Warmup)
## Chain 3: Iteration: 1000 / 2000 [ 50%]  (Warmup)
## Chain 3: Iteration: 1001 / 2000 [ 50%]  (Sampling)
## Chain 3: Iteration: 1200 / 2000 [ 60%]  (Sampling)
## Chain 3: Iteration: 1400 / 2000 [ 70%]  (Sampling)
## Chain 3: Iteration: 1600 / 2000 [ 80%]  (Sampling)
## Chain 3: Iteration: 1800 / 2000 [ 90%]  (Sampling)
## Chain 3: Iteration: 2000 / 2000 [100%]  (Sampling)
## Chain 3: 
## Chain 3:  Elapsed Time: 0.93766 seconds (Warm-up)
## Chain 3:                0.927092 seconds (Sampling)
## Chain 3:                1.86475 seconds (Total)
## Chain 3: 
## 
## SAMPLING FOR MODEL 'multiple_NB_regression' NOW (CHAIN 4).
## Chain 4: 
## Chain 4: Gradient evaluation took 6.8e-05 seconds
## Chain 4: 1000 transitions using 10 leapfrog steps per transition would take 0.68 seconds.
## Chain 4: Adjust your expectations accordingly!
## Chain 4: 
## Chain 4: 
## Chain 4: Iteration:    1 / 2000 [  0%]  (Warmup)
## Chain 4: Iteration:  200 / 2000 [ 10%]  (Warmup)
## Chain 4: Iteration:  400 / 2000 [ 20%]  (Warmup)
## Chain 4: Iteration:  600 / 2000 [ 30%]  (Warmup)
## Chain 4: Iteration:  800 / 2000 [ 40%]  (Warmup)
## Chain 4: Iteration: 1000 / 2000 [ 50%]  (Warmup)
## Chain 4: Iteration: 1001 / 2000 [ 50%]  (Sampling)
## Chain 4: Iteration: 1200 / 2000 [ 60%]  (Sampling)
## Chain 4: Iteration: 1400 / 2000 [ 70%]  (Sampling)
## Chain 4: Iteration: 1600 / 2000 [ 80%]  (Sampling)
## Chain 4: Iteration: 1800 / 2000 [ 90%]  (Sampling)
## Chain 4: Iteration: 2000 / 2000 [100%]  (Sampling)
## Chain 4: 
## Chain 4:  Elapsed Time: 1.03262 seconds (Warm-up)
## Chain 4:                0.833077 seconds (Sampling)
## Chain 4:                1.86569 seconds (Total)
## Chain 4:
samps_NB <- rstan::extract(fitted_model_NB)
y_rep <- samps_NB$y_rep

ppc_stat_grouped(
  y = stan_dat_simple$complaints, 
  yrep = y_rep, 
  group = pest_data$building_id, 
  stat = 'mean',
  binwidth = 0.2
)

Lab 5

5 Select some of the variables that give information at the building level (live in super, age of building, average tentant age, and monthly average rent) and arrange them into a matrix called building_data.

N_months <- length(unique(pest_data$date))

# Add some IDs for building and month
pest_data <- pest_data %>%
  mutate(
    building_fac = factor(building_id, levels = unique(building_id)),
    building_idx = as.integer(building_fac),
    ids = rep(1:N_months, N_buildings),
    mo_idx = lubridate::month(date)
  )

# Center and rescale the building specific data
building_data <- pest_data %>%
    select(
      building_idx,
      live_in_super,
      age_of_building,
      total_sq_foot,
      average_tenant_age,
      monthly_average_rent
    ) %>%
    unique() %>%
    arrange(building_idx) %>%
    select(-building_idx) %>%
    scale(scale=FALSE) %>%
    as.data.frame() %>%
    mutate( # scale by constants
      age_of_building = age_of_building / 10,
      total_sq_foot = total_sq_foot / 10000,
      average_tenant_age = average_tenant_age / 10,
      monthly_average_rent = monthly_average_rent / 1000
    ) %>%
    as.matrix()

str(building_data)
##  num [1:10, 1:5] -0.3 -0.3 -0.3 -0.3 0.7 -0.3 -0.3 0.7 -0.3 0.7 ...
##  - attr(*, "dimnames")=List of 2
##   ..$ : NULL
##   ..$ : chr [1:5] "live_in_super" "age_of_building" "total_sq_foot" "average_tenant_age" ...
stan_dat_hier <-
  with(pest_data,
        list(complaints = complaints,
             traps = traps,
             N = length(traps),
             J = N_buildings,
             log_sq_foot = log(pest_data$total_sq_foot/1e4),
             building_data = building_data[,-3],
             mo_idx = as.integer(as.factor(date)),
             K = 4,
             building_idx = building_idx
             )
       )
str(stan_dat_hier)
## List of 9
##  $ complaints   : num [1:120] 1 3 0 1 0 0 4 3 2 2 ...
##  $ traps        : num [1:120] 8 8 9 10 11 11 10 10 9 9 ...
##  $ N            : int 120
##  $ J            : int 10
##  $ log_sq_foot  : num [1:120] 1.42 1.42 1.42 1.42 1.42 ...
##  $ building_data: num [1:10, 1:4] -0.3 -0.3 -0.3 -0.3 0.7 -0.3 -0.3 0.7 -0.3 0.7 ...
##   ..- attr(*, "dimnames")=List of 2
##   .. ..$ : NULL
##   .. ..$ : chr [1:4] "live_in_super" "age_of_building" "average_tenant_age" "monthly_average_rent"
##  $ mo_idx       : int [1:120] 1 2 3 4 5 6 7 8 9 10 ...
##  $ K            : num 4
##  $ building_idx : int [1:120] 1 1 1 1 1 1 1 1 1 1 ...

6 Model the variation across buildings usign a varying intercept Negative Binomial hierarchical model.

Using stan write, compile and fit the following varying intercept model

\[ \text{complaints}_{ib} \sim \text{Neg-Binomial}(\lambda_{ib}, \phi) \\ \lambda_{ib} = \exp{(\eta_{ib})} \\ \eta_{ib} = \mu_{b(i)} + \beta \, {\rm traps}_{i} + \text{log_sq_foot}_i \\ \mu_b \sim \text{Normal}(\alpha + \beta_{\rm super}\, {\rm super}_b + \ldots + \beta_{\rm mar}\, {\rm mar}_b , \sigma_{\mu}) \]

comp_model_NB_hier <- stan_model('hier_NB_regression.stan')
fitted_model_NB_hier <- sampling(comp_model_NB_hier, data = stan_dat_hier,
  chains = 4, cores = 4, iter = 4000)

7 Do you have any divergent transitions?

samps_hier_NB <- rstan::extract(fitted_model_NB_hier)
print(fitted_model_NB_hier, pars = c('sigma_mu','beta','alpha','phi','mu'))
## Inference for Stan model: hier_NB_regression.
## 4 chains, each with iter=4000; warmup=2000; thin=1; 
## post-warmup draws per chain=2000, total post-warmup draws=8000.
## 
##           mean se_mean   sd  2.5%   25%   50%   75% 97.5% n_eff Rhat
## sigma_mu  0.24    0.01 0.17  0.04  0.12  0.21  0.33  0.66   244 1.02
## beta     -0.23    0.00 0.06 -0.35 -0.27 -0.23 -0.19 -0.12   633 1.01
## alpha     1.27    0.02 0.41  0.47  1.00  1.28  1.53  2.09   746 1.01
## phi       1.60    0.02 0.34  1.05  1.37  1.54  1.78  2.35   367 1.01
## mu[1]     1.30    0.02 0.53  0.25  0.95  1.29  1.66  2.33   865 1.00
## mu[2]     1.25    0.02 0.50  0.27  0.92  1.25  1.59  2.25   761 1.01
## mu[3]     1.41    0.02 0.46  0.52  1.11  1.43  1.69  2.33   813 1.01
## mu[4]     1.46    0.02 0.46  0.58  1.14  1.47  1.76  2.38   870 1.00
## mu[5]     1.08    0.01 0.40  0.29  0.82  1.07  1.34  1.92   919 1.00
## mu[6]     1.19    0.02 0.46  0.25  0.86  1.20  1.52  2.07   479 1.01
## mu[7]     1.48    0.02 0.49  0.51  1.15  1.50  1.80  2.45   924 1.01
## mu[8]     1.23    0.02 0.41  0.47  0.93  1.21  1.50  2.08   591 1.01
## mu[9]     1.42    0.02 0.53  0.35  1.06  1.44  1.74  2.47   858 1.01
## mu[10]    0.87    0.02 0.36  0.19  0.64  0.88  1.09  1.64   518 1.00
## 
## Samples were drawn using NUTS(diag_e) at Sat May 25 12:11:59 2019.
## For each parameter, n_eff is a crude measure of effective sample size,
## and Rhat is the potential scale reduction factor on split chains (at 
## convergence, Rhat=1).
mcmc_trace(
  as.array(fitted_model_NB_hier,pars = 'sigma_mu'),
  np = nuts_params(fitted_model_NB_hier),
  window = c(500,1000)
)

# assign to object so we can compare to another plot later
scatter_with_divs <- mcmc_scatter(
  as.array(fitted_model_NB_hier),
  pars = c("mu[4]", 'sigma_mu'),
  transform = list('sigma_mu' = "log"),
  np = nuts_params(fitted_model_NB_hier)
)
scatter_with_divs

N_sims <- 1000
log_sigma <- rep(NA, N_sims)
theta <- rep(NA, N_sims)
for (j in 1:N_sims) {
  log_sigma[j] <- rnorm(1, mean = 0, sd = 1)
  theta[j] <- rnorm(1, mean = 0, sd = exp(log_sigma[j]))
}
draws <- cbind("mu" = theta, "log(sigma_mu)" = log_sigma)
mcmc_scatter(draws)

parcoord_with_divs <- mcmc_parcoord(
  as.array(fitted_model_NB_hier, pars = c("sigma_mu", "mu")),
  np = nuts_params(fitted_model_NB_hier)
)
parcoord_with_divs

8 We see evidence that our problems concentrate when \(\texttt{sigma_mu}\) is small. Reparametrize the model using the non-centered parametrization and check diagnostics. The distribution of \(\texttt{mu}\) does not change: \[ \mu_b \sim \text{Normal}(\alpha + \texttt{building_data} \, \zeta, \sigma_{\mu}) \] We add an auxiliary variable in the parameters block \(\texttt{mu_raw}\sim \text{Normal}(0, 1)\) and we move \(\texttt{mu}\) in the transformed parameters block.

transformed parameters {
  vector[J] mu;
  mu = alpha + building_data * zeta + sigma_mu * mu_raw;
}
comp_model_NB_hier_ncp <- stan_model('hier_NB_regression_ncp.stan')
fitted_model_NB_hier_ncp <- sampling(comp_model_NB_hier_ncp, data = stan_dat_hier, chains = 4, cores = 4)
print(fitted_model_NB_hier_ncp, pars = c('sigma_mu','beta','alpha','phi','mu'))
## Inference for Stan model: hier_NB_regression_ncp.
## 4 chains, each with iter=2000; warmup=1000; thin=1; 
## post-warmup draws per chain=1000, total post-warmup draws=4000.
## 
##           mean se_mean   sd  2.5%   25%   50%   75% 97.5% n_eff Rhat
## sigma_mu  0.23    0.00 0.17  0.01  0.10  0.20  0.32  0.65  1175 1.01
## beta     -0.23    0.00 0.06 -0.36 -0.27 -0.23 -0.19 -0.11  2823 1.00
## alpha     1.26    0.01 0.44  0.42  0.97  1.27  1.55  2.14  2694 1.00
## phi       1.59    0.01 0.34  1.05  1.35  1.54  1.79  2.35  4429 1.00
## mu[1]     1.28    0.01 0.55  0.19  0.92  1.29  1.64  2.37  2621 1.00
## mu[2]     1.23    0.01 0.53  0.17  0.89  1.23  1.57  2.29  2724 1.00
## mu[3]     1.40    0.01 0.50  0.47  1.06  1.40  1.73  2.41  3014 1.00
## mu[4]     1.43    0.01 0.49  0.48  1.10  1.42  1.76  2.40  2994 1.00
## mu[5]     1.08    0.01 0.42  0.26  0.79  1.08  1.35  1.92  3222 1.00
## mu[6]     1.19    0.01 0.49  0.23  0.86  1.20  1.50  2.18  2548 1.00
## mu[7]     1.46    0.01 0.52  0.45  1.12  1.46  1.80  2.51  3110 1.00
## mu[8]     1.24    0.01 0.43  0.43  0.95  1.23  1.53  2.08  3288 1.00
## mu[9]     1.42    0.01 0.57  0.33  1.05  1.43  1.80  2.54  2813 1.00
## mu[10]    0.87    0.01 0.37  0.17  0.61  0.86  1.12  1.60  3575 1.00
## 
## Samples were drawn using NUTS(diag_e) at Sat May 25 12:12:13 2019.
## For each parameter, n_eff is a crude measure of effective sample size,
## and Rhat is the potential scale reduction factor on split chains (at 
## convergence, Rhat=1).
scatter_no_divs <- mcmc_scatter(
  as.array(fitted_model_NB_hier_ncp),
  pars = c("mu[4]", 'sigma_mu'),
  transform = list('sigma_mu' = "log"),
  np = nuts_params(fitted_model_NB_hier_ncp)
)
bayesplot_grid(scatter_with_divs, scatter_no_divs,
               grid_args = list(ncol = 2), ylim = c(-11, 1))

parcoord_no_divs <- mcmc_parcoord(
  as.array(fitted_model_NB_hier_ncp, pars = c("sigma_mu", "mu")),
  np = nuts_params(fitted_model_NB_hier_ncp)
)
bayesplot_grid(parcoord_with_divs, parcoord_no_divs,
               ylim = c(-3, 3))

samps_NB_hier_ncp <- rstan::extract(fitted_model_NB_hier_ncp, pars = c('y_rep','inv_phi'))
y_rep <- as.matrix(fitted_model_NB_hier_ncp, pars = "y_rep")
ppc_dens_overlay(stan_dat_hier$complaints, y_rep[1:200,])

ppc_stat_grouped(
  y = stan_dat_hier$complaints,
  yrep = y_rep,
  group = pest_data$building_id,
  stat = 'mean',
  binwidth = 0.5
)

ppc_stat_grouped(
  y = stan_dat_hier$complaints,
  yrep = y_rep,
  group = pest_data$building_id,
  stat = 'sd',
  binwidth = 0.5
)

ppc_intervals(
  y = stan_dat_hier$complaints,
  yrep = y_rep,
  x = stan_dat_hier$traps
) +
  labs(x = "Number of traps", y = "Number of complaints")

mean_y_rep <- colMeans(y_rep)
mean_inv_phi <- mean(as.matrix(fitted_model_NB_hier_ncp, pars = "inv_phi"))
std_resid <- (stan_dat_hier$complaints - mean_y_rep) / sqrt(mean_y_rep + mean_y_rep^2*mean_inv_phi)
qplot(mean_y_rep, std_resid) + hline_at(2) + hline_at(-2)

Lab 6

9 Try to expand the previous model with varying slope.

\[ \text{complaints}_{ib} \sim \text{Neg-Binomial}(\lambda_{ib}, \phi) \\ \lambda_{ib} = \exp{(\eta_{ib})}\\ \eta_{ib} = \mu_{b(i)} + \kappa_{b(i)} \, \texttt{traps}_{ib} + \text{log_sq_foot}_i \\ \mu_b \sim \text{Normal}(\alpha + \texttt{building_data} \, \zeta, \sigma_{\mu}) \\ \kappa_b \sim \text{Normal}(\beta + \texttt{building_data} \, \gamma, \sigma_{\kappa}) \]

stan_dat_hier <- readRDS('pest_data_longer_stan_dat.RDS')
comp_model_NB_hier_slopes <- stan_model('hier_NB_regression_ncp_slopes_mod.stan')
fitted_model_NB_hier_slopes <-
  sampling(
    comp_model_NB_hier_slopes,
    data = stan_dat_hier,
    chains = 4, cores = 4,
    control = list(adapt_delta = 0.95)
  )
mcmc_hist(
  as.matrix(fitted_model_NB_hier_slopes, pars = "sigma_kappa"),
  binwidth = 0.005
)

print(fitted_model_NB_hier_slopes, pars = c('kappa','beta','alpha','phi','sigma_mu','sigma_kappa','mu'))
## Inference for Stan model: hier_NB_regression_ncp_slopes_mod.
## 4 chains, each with iter=2000; warmup=1000; thin=1; 
## post-warmup draws per chain=1000, total post-warmup draws=4000.
## 
##              mean se_mean   sd  2.5%   25%   50%   75% 97.5% n_eff Rhat
## kappa[1]    -0.02    0.00 0.07 -0.14 -0.07 -0.03  0.02  0.16  1216    1
## kappa[2]    -0.42    0.00 0.10 -0.62 -0.48 -0.41 -0.35 -0.24  2087    1
## kappa[3]    -0.59    0.00 0.10 -0.79 -0.66 -0.59 -0.52 -0.39  5437    1
## kappa[4]    -0.22    0.00 0.07 -0.36 -0.27 -0.22 -0.18 -0.09  3793    1
## kappa[5]    -0.60    0.00 0.09 -0.79 -0.66 -0.60 -0.54 -0.43  5888    1
## kappa[6]    -0.44    0.00 0.10 -0.68 -0.49 -0.43 -0.37 -0.26  2677    1
## kappa[7]    -0.31    0.00 0.07 -0.44 -0.36 -0.31 -0.27 -0.18  5954    1
## kappa[8]    -0.23    0.00 0.15 -0.56 -0.32 -0.22 -0.12  0.04  2319    1
## kappa[9]     0.08    0.00 0.06 -0.04  0.04  0.08  0.12  0.20  6068    1
## kappa[10]   -0.72    0.00 0.16 -1.01 -0.83 -0.73 -0.63 -0.38  1418    1
## beta        -0.35    0.00 0.06 -0.48 -0.38 -0.35 -0.31 -0.23  1965    1
## alpha        1.41    0.01 0.31  0.73  1.23  1.42  1.61  1.98  2521    1
## phi          1.61    0.00 0.19  1.27  1.47  1.59  1.73  2.03  4713    1
## sigma_mu     0.48    0.02 0.40  0.02  0.17  0.38  0.70  1.46   690    1
## sigma_kappa  0.13    0.00 0.09  0.03  0.07  0.10  0.16  0.34   751    1
## mu[1]        0.31    0.02 0.71 -1.43 -0.06  0.40  0.79  1.49  1221    1
## mu[2]        1.65    0.01 0.52  0.72  1.29  1.61  1.98  2.74  1950    1
## mu[3]        2.13    0.00 0.32  1.53  1.92  2.13  2.35  2.77  5512    1
## mu[4]        1.48    0.01 0.51  0.48  1.16  1.48  1.80  2.48  3991    1
## mu[5]        2.39    0.01 0.43  1.60  2.09  2.39  2.67  3.24  6340    1
## mu[6]        1.91    0.01 0.39  1.21  1.66  1.88  2.11  2.82  2805    1
## mu[7]        2.69    0.00 0.25  2.22  2.52  2.68  2.85  3.17  5293    1
## mu[8]       -0.56    0.02 0.94 -2.28 -1.19 -0.60  0.04  1.41  2588    1
## mu[9]        0.22    0.01 0.58 -0.88 -0.17  0.22  0.60  1.40  6079    1
## mu[10]       1.83    0.03 1.11 -0.78  1.26  1.98  2.59  3.61  1142    1
## 
## Samples were drawn using NUTS(diag_e) at Sat May 25 12:13:57 2019.
## For each parameter, n_eff is a crude measure of effective sample size,
## and Rhat is the potential scale reduction factor on split chains (at 
## convergence, Rhat=1).
mcmc_hist(
  as.matrix(fitted_model_NB_hier_slopes, pars = "beta"),
  binwidth = 0.005
)

y_rep <- as.matrix(fitted_model_NB_hier_slopes, pars = "y_rep")
ppc_dens_overlay(
  y = stan_dat_hier$complaints,
  yrep = y_rep[1:200,]
)

10 Consider to extend your model adding a log-additive monthly effect \(\texttt{mo}_t\).

select_vec <- which(stan_dat_hier$mo_idx %in% 1:12)
ppc_stat_grouped(
  y = stan_dat_hier$complaints[select_vec],
  yrep = y_rep[,select_vec],
  group = stan_dat_hier$mo_idx[select_vec],
  stat = 'mean'
) + xlim(0, 11)

The linear predictor of the random intercept and random slope Negative Binomial model is then:

\[ \eta_{bt} = \mu_{b} + \kappa_{b} \, \texttt{traps}_{bt} + \texttt{mo}_t + \text{log_sq_foot}_b \]

Then define an autoregressive prior on the monthly effects:

\[ \texttt{mo}_t \sim \text{Normal}(\rho \, \texttt{mo}_{t-1}, \sigma_\texttt{mo}) \\ \equiv \\ \texttt{mo}_t = \rho \, \texttt{mo}_{t-1} +\epsilon_t , \quad \epsilon_t \sim \text{Normal}(0, \sigma_\texttt{mo}) \\ \quad \rho \in [-1,1] \]

Using the stationary assumption of the AR models, find the marginal distribution for \(\texttt{mo}_1\).

The marginal variance:

\[Var(\texttt{mo}_{t})=Var(\rho \texttt{mo}_{t-1}) + Var(\epsilon_t)\] by independence of \(\epsilon_{t-1}\) and \(\epsilon_{t}\). Then, by stationarity \[Var(\texttt{mo}_{t})=\rho^2 Var(\texttt{mo}_{t}) + \sigma^2_{mo}\] \[Var(\texttt{mo}_{t})=\frac{\sigma^2_{mo}}{1-\rho^2}\]

The marginal mean \[E(\texttt{mo}_{t})=E(\rho \texttt{mo}_{t-1}) + E(\epsilon_t)\] \[E(\texttt{mo}_{t})=\frac{0}{1-\rho}=0\]

for \(\rho\ne 1\).

Thus,

\[\texttt{mo}_{1} \sim Normal\left (0,\frac{\sigma_{mo}}{\sqrt{1-\rho^2}} \right)\]

Use the follow setting to define the prior on the parameter \(\rho\):

\[ \rho_{\text{raw}} \in [0, 1] \\ \rho = 2 \times \rho_{\text{raw}} - 1\\ \rho_{\text{raw}} \sim Beta(10,5) \]

comp_model_NB_hier_mos <- stan_model('hier_NB_regression_ncp_slopes_mod_mos.stan')
fitted_model_NB_hier_mos <- sampling(comp_model_NB_hier_mos, data = stan_dat_hier, chains = 4, cores = 4, control = list(adapt_delta = 0.9))
y_rep <- as.matrix(fitted_model_NB_hier_mos, pars = "y_rep")
ppc_dens_overlay(
  y = stan_dat_hier$complaints,
  yrep = y_rep[1:200,]
)

select_vec <- which(stan_dat_hier$mo_idx %in% 1:12)
ppc_stat_grouped(
  y = stan_dat_hier$complaints[select_vec],
  yrep = y_rep[,select_vec],
  group = stan_dat_hier$mo_idx[select_vec],
  stat = 'mean'
)

# overlay prior density curve on posterior draws
gen_rho_prior <- function(x) {
  alpha <- 10; beta <- 5
  a <- -1; c <- 1
  lp <- (alpha - 1) * log(x - a) +
        (beta - 1) * log(c - x) -
        (alpha + beta - 1) * log(c - a) -
         lbeta(alpha, beta)
  return(exp(lp))
}
mcmc_hist(as.matrix(fitted_model_NB_hier_mos, pars = "rho"),
          freq = FALSE, binwidth = 0.01) +
  overlay_function(fun = gen_rho_prior) +
  xlim(-1,1)

print(fitted_model_NB_hier_mos, pars = c('rho','sigma_mu','sigma_kappa','gamma'))
## Inference for Stan model: hier_NB_regression_ncp_slopes_mod_mos.
## 4 chains, each with iter=2000; warmup=1000; thin=1; 
## post-warmup draws per chain=1000, total post-warmup draws=4000.
## 
##              mean se_mean   sd  2.5%   25%   50%   75% 97.5% n_eff Rhat
## rho          0.78    0.00 0.08  0.59  0.73  0.79  0.84  0.91  1517    1
## sigma_mu     0.31    0.01 0.24  0.01  0.12  0.26  0.45  0.88  1498    1
## sigma_kappa  0.09    0.00 0.05  0.01  0.05  0.08  0.11  0.22  1133    1
## gamma[1]    -0.19    0.00 0.11 -0.40 -0.25 -0.19 -0.13  0.02  2049    1
## gamma[2]     0.11    0.00 0.08 -0.03  0.07  0.11  0.16  0.26  1843    1
## gamma[3]     0.11    0.00 0.15 -0.17  0.02  0.11  0.20  0.42  2025    1
## gamma[4]     0.00    0.00 0.06 -0.14 -0.04  0.00  0.04  0.11  2173    1
## 
## Samples were drawn using NUTS(diag_e) at Sat May 25 12:17:44 2019.
## For each parameter, n_eff is a crude measure of effective sample size,
## and Rhat is the potential scale reduction factor on split chains (at 
## convergence, Rhat=1).
ppc_intervals(
  y = stan_dat_hier$complaints,
  yrep = y_rep,
  x = stan_dat_hier$traps
) +
  labs(x = "Number of traps", y = "Number of complaints")

11 Compare the last two models computing the approximate leave-one-out cross-validation.

comp_model_NB_hier_slopes_llik <- stan_model('hier_NB_regression_ncp_slopes_mod_loglik.stan')

fitted_model_NB_hier_slopes_llik <-
  sampling(
    comp_model_NB_hier_slopes_llik,
    data = stan_dat_hier,
    chains = 4, cores = 4,
    control = list(adapt_delta = 0.95)
  )
comp_model_NB_hier_mos_llik <- stan_model('hier_NB_regression_ncp_slopes_mod_mos_loglik.stan')

fitted_model_NB_hier_mos_llik <-
  sampling(
    comp_model_NB_hier_mos_llik,
    data = stan_dat_hier,
    chains = 4, cores = 4,
    control = list(adapt_delta = 0.95)
  )
library(loo)
log_lik_slopes <- extract_log_lik(fitted_model_NB_hier_slopes_llik)
loo_slopes <- loo(log_lik_slopes)
loo_slopes
## 
## Computed from 4000 by 360 log-likelihood matrix
## 
##          Estimate   SE
## elpd_loo   -874.6 28.6
## p_loo        17.1  2.3
## looic      1749.3 57.2
## ------
## Monte Carlo SE of elpd_loo is 0.1.
## 
## Pareto k diagnostic values:
##                          Count Pct.    Min. n_eff
## (-Inf, 0.5]   (good)     356   98.9%   443       
##  (0.5, 0.7]   (ok)         4    1.1%   4000      
##    (0.7, 1]   (bad)        0    0.0%   <NA>      
##    (1, Inf)   (very bad)   0    0.0%   <NA>      
## 
## All Pareto k estimates are ok (k < 0.7).
## See help('pareto-k-diagnostic') for details.
log_lik_mos <- extract_log_lik(fitted_model_NB_hier_mos_llik)
loo_mos <- loo(log_lik_mos)
loo_mos
## 
## Computed from 4000 by 360 log-likelihood matrix
## 
##          Estimate   SE
## elpd_loo   -744.4 26.8
## p_loo        42.6  3.8
## looic      1488.7 53.6
## ------
## Monte Carlo SE of elpd_loo is NA.
## 
## Pareto k diagnostic values:
##                          Count Pct.    Min. n_eff
## (-Inf, 0.5]   (good)     351   97.5%   915       
##  (0.5, 0.7]   (ok)         8    2.2%   246       
##    (0.7, 1]   (bad)        1    0.3%   157       
##    (1, Inf)   (very bad)   0    0.0%   <NA>      
## See help('pareto-k-diagnostic') for details.
compare(loo_slopes, loo_mos)
## elpd_diff        se 
##     130.3      12.5